<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>盒子移动</title>
    <style>
        body {}

        #div {
            width: 100px;
            height: 100px;
            background-color: #2e8a8d;
            position: absolute;

        }

        button {
            position: relative;
            top: 120px;
        }
    </style>
</head>

<body>
    <div id="div"></div>
    <button>点击开始</button>
    <button>点击结束</button>
    <script>
        let btn = document.getElementsByTagName("button");
        let div = document.getElementById("div");
        let body = document.body;
        let num = 0
        let timer = null

        btn[0].onclick = function () {
            let speed = 20
            if (timer == null) {
                timer = setInterval(function () {
                    num += speed
                    div.style.left = num + "px";
                    // API: offsetWidth: 获取元素的宽度，包括padding和border，不包括margin
                    if (num >= body.offsetWidth - div.offsetWidth || num <= 0)
                        speed = -speed

                }, 100)
            }
        }
        btn[1].onclick = function () {
            clearInterval(timer)
            timer = null
        }
    </script>
</body>

</html>